package com.killer.factory;

import com.killer.pojo.BeanDefinition;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：Killer
 * @date ：Created in 20-10-26 上午10:03
 * @description：${description}
 * @modified By：
 * @version: version
 */
public class DefaultListableBeanFactory implements BeanFactory {


    /**
     * 用于保存解析出来的bean对象 key:bean的id  value:解析后的bean定义对象
     */
    private Map<String, BeanDefinition> registerMap = new ConcurrentHashMap<String,BeanDefinition>();

    /**
     * 单例池对象
     */
    private Map<String, Object> singletonObject = new ConcurrentHashMap<String, Object>();

    /**
     * 这里为了简便，用二级缓存解决循环依赖，如果用到动态代理的话用三级缓存实现会更优雅，这里暂不考虑动态代理
     */
    private Map<String,Object> earlySingleton=new ConcurrentHashMap<String,Object>();

    @Override
    public Object getBean(String name) {
        //先从单例池获取
        Object object = singletonObject.get(name);
        if (object == null) {
            //单例池为空，则从二级缓存中获取(提前暴露的对象)
            object = earlySingleton.get(name);
        }
        return object;
    }

    public void registerBean(BeanDefinition beanDefinition) {
        registerMap.put(beanDefinition.getId(), beanDefinition);
    }

    public BeanDefinition getBeanDefinition(String id){
        return registerMap.get(id);
    }

    public Map<String, BeanDefinition> getRegisterFactory(){
        return registerMap;
    }

    public void earlyEsposeObject(String beanId, Object object) {
        earlySingleton.put(beanId, object);
    }

    public void finishBeanCreation(String name, Object object) {
        earlySingleton.remove(name);
        singletonObject.put(name, object);
    }
}
